package com.a1573595.musicplayer.songList

import android.content.Context
import okhttp3.Request
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.a1573595.musicplayer.databinding.ActivitySearchMusicBinding
import com.a1573595.musicplayer.dbHelper.Music_DatabaseInitializer
import com.a1573595.musicplayer.dbHelper.OnLineMusicDatabaseHelper
import com.a1573595.musicplayer.model.Music
import android.app.Service
import android.os.Environment
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import okhttp3.OkHttpClient
import java.util.Locale


class SearchMusicActivity : AppCompatActivity() {
    private lateinit var viewBinding: ActivitySearchMusicBinding
    private val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = ActivitySearchMusicBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)

        val dbHelper = OnLineMusicDatabaseHelper(this)

        // 检查数据库是否已经初始化
        if (!isDatabaseInitialized()) { // 未初始化
            Music_DatabaseInitializer(this).initialize()
            setDatabaseInitialized()
        }

        viewBinding.btnSearch.setOnClickListener {
            val musicName = viewBinding.edMusicName.text.toString()
            searchMusicInDatabase(musicName)
        }
    }

    private fun searchMusicInDatabase(musicName: String) {
        val dbHelper = OnLineMusicDatabaseHelper(this)
        val normalizedMusicName = musicName.trim().toLowerCase(Locale.ROOT)
        val music = dbHelper.findMusicByName(normalizedMusicName)
        if (music != null) {
            //Log.d("SearchMusicActivity", "find music: $music")
            downloadMusic(music.musicURL, music.musicName)
        } else {

            Toast.makeText(this, "未查找到相应音乐QAQ", Toast.LENGTH_SHORT).show()
        }
    }

//    private fun downloadMusic(musicURL: String) {
//        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(musicURL))
//        if (intent.resolveActivity(packageManager) != null) {
//            startActivity(intent)
//        } else {
//            Toast.makeText(this, "Cannot open browser to download music", Toast.LENGTH_SHORT).show()
//        }
//    }

//    private fun downloadMusic(musicURL: String,musicName: String) {
//        Thread {
//            try {
//                val request = Request.Builder().url(musicURL).build()
//                val response = client.newCall(request).execute()
//                if (response.isSuccessful) {
//                    val file = File(cacheDir, "$musicName.mp3")
//                    val fos = FileOutputStream(file)
//                    fos.write(response.body?.bytes())
//
//                    runOnUiThread {
//                        Toast.makeText(this, "download success", Toast.LENGTH_SHORT).show()
//                    }
//
//                    fos.close()
//                }
//            } catch (e: IOException) {
//                runOnUiThread {
//                    Toast.makeText(this, "Cannot open browser to download music", Toast.LENGTH_SHORT).show()
//                }
//            }
//        }.start()
//    }

    private fun downloadMusic(musicURL: String, musicName: String) {
        Thread {
            try {
                val request = Request.Builder().url(musicURL).build()
                val response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    val musicDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "/Music")
                    if (!musicDir.exists()) {
                        musicDir.mkdirs()
                    }
                    Log.d("SearchMusicActivity", "musicDir: $musicDir")
                    val file = File(musicDir, "$musicName.mp3")
                    val fos = FileOutputStream(file)
                    fos.write(response.body?.bytes())

                    runOnUiThread {
                        Toast.makeText(this, "下载成功，请重启后在列表中查看", Toast.LENGTH_SHORT).show()
                    }

                    fos.close()

                }
            } catch (e: IOException) {
                runOnUiThread {
                    Toast.makeText(this, "下载失败，请检查网络设置", Toast.LENGTH_SHORT).show()
                }
            }
        }.start()
    }

    private fun isDatabaseInitialized(): Boolean {
        val sharedPreferences = getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
        return sharedPreferences.getBoolean("music_database_initialized", false)
    }

    // 设置数据库已经初始化的方法
    private fun setDatabaseInitialized() {
        val sharedPreferences = getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
        with(sharedPreferences.edit()) {
            putBoolean("music_database_initialized", true)
            apply()
        }
    }
}